// pages/Goods/GoodDetail/GoodDetail.js
//获取应用实例
const app = getApp();
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getGoodsPicture , getGoodsSpecInfo , getShoppingCartGoods , goodsCollection , updateShoppingCartGoods , getGoodsCollection } from '../../../api/goods';
import{ queryGoodsLists , queryGoodsCommonConfig , queryGoodsFreightConfig } from '../../../api/goods';
import { queryGoodsPurchaseRecord } from '../../../api/order';
import { queryGoodsFreeFreightMark } from '../../../api/user';
import { queryAppInforMation , queryGoodsCloseConfig } from '../../../api/brand';
import { formatTime , checkFile } from '../../../utils/util';
const regeneratorRuntime = require('../../../common/runtime');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    contactUrl: app.globalData.global.contactUrl,
    contactId: app.globalData.global.contactId,
    assetsAddress: assetsAddress,
    goods: {},
    goodsId: '',
    isShowZhb: false,
    isShowBackTop: false,
    navBgColor: 'none',
    titleColor: 'white',
    goodsBanner: [], // 商品轮播图
    goodsDetailPic: [], // 商品详情图
    goodsSpecInfo: {}, // 商品规格
    goodsSpecList: [],
    gradeColorList: [], // 等级列表
    grade: '',
    colorId: '',
    areaName: '', // 分区名称 
    isReachStandard: false, // 上月积分是否达标
    reachStandardList: [
      {id: 0, label: '免打包费' , url: `${assetsAddress}/goodsDetail/jcdbIcon.png`},
      {id: 1, label: '免运输费' , url: `${assetsAddress}/goodsDetail/myfIcon.png`},
      {id: 2, label: '极速售后' , url: `${assetsAddress}/goodsDetail/jsshhIcon.png`},
    ],
    goodsRecord: [], // 商品购买记录
    goodsRecordTotal: 0, // 购买人数
    shoppingCartGoodsSum: 0, // 购物车数量
    isShowPicContent: false, // 是否大图展示商品详情图片
    paddingBtm: 0,
    item: {},
    countDownTime: 0, // 秒杀倒计时的秒数
    collectId: '',
    storehouseName: '', // 仓库名称
    hasBegin: false, // 秒杀是否开始
    id: '',
    merchantId: '', // 商家ID
    selGrade: '',
    selColorId: '',
    remarks: '',
    description: '',
    imgType: 'image',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.item){
      console.log(JSON.parse(options.item),'item')
      var item = JSON.parse(options.item);
      this.setData({
        item: JSON.parse(options.item),
        storehouseName: wx.getStorageSync('storehouseName'),
        // goodsId: item.goodsId ? item.goodsId : item.id,
        colorId: options.colorId ? JSON.parse(options.colorId) : '',
        selGrade: options.grade ? JSON.parse(options.grade) : '',
        selColorId: options.colorId ? JSON.parse(options.colorId) : '',
        remarks: options.remarks ? decodeURIComponent(options.remarks) : '',
        description: options.description ? decodeURIComponent(options.description) : 'description',
        'id': options.id ? options.id : '',
        'merchantId': options.merchantId ? options.merchantId : '',
      })
    }
    this.getGoods();
    this._getShoppingCartGoods();
    this._queryGoodsPurchaseRecord();
    this._queryGoodsArea();
    const res = wx.getSystemInfoSync()
    const { screenHeight, safeArea: { bottom } } = res
    if (screenHeight && bottom){
      let safeBottom = screenHeight - bottom
      this.setData({
        paddingBtm: 50 + safeBottom
      })
    }else{
      this.setData({
        paddingBtm: 50
      })
    }
    wx.setStorageSync('params', '')
    wx.setStorageSync('pathName','')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  onPageScroll (e) { 
    // console.log(e,'页面滚动')
    if(e.scrollTop > 150 && this.data.navBgColor != 'white'){
      this.setData({
        navBgColor: 'white',
        isShowBackTop: true,
        titleColor: '#333333'
      })
    }else if(e.scrollTop < 150 && this.data.navBgColor == 'white'){
      this.setData({
        navBgColor: 'none',
        isShowBackTop: false,
        titleColor: '#FFFFFF'
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.setStorageSync('shoppingCartId', '')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    var scene = `${userId}---${JSON.stringify(this.data.item)}---goodsDetail`
    console.log(scene,'scene')
    return {
      title: this.data.shareTitle,
      // path: '/pages/Welcome/Welcome?scene='+userId,
      path: '/pages/Welcome/Welcome?scene='+scene,
    }
  },
  // 返回页面
  back(){
    wx.navigateBack({
      delta: 1,
    })
  },
  // 获取商品详情信息
  getGoods(){
    let _this = this;
    const { item , grade , colorId , id , merchantId } = _this.data;
    console.log(id,'商品ID')
    queryGoodsLists({areaId: item.areaId,storehouseId: item.storehouseId,cateId: item.cateId,goodsId: item.goodsId,grade: grade,colorId: colorId,id: id,merchantId: merchantId})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          if(_this.data.grade == ''){
            var gradeColorList = [];
            gradeColorList.push({
              'grade': res.data.content[0].grade,
              'colors': []
            });
            // var selGoods = {};
            for (let index = 0; index < res.data.content.length; index++) {
              const item = res.data.content[index];
              // if(gradeList.indexOf(item.grade) == -1){
              //   gradeList.push(item.grade)
              // }
              if(gradeColorList.find(grade => grade.grade == item.grade)){
                var i =  gradeColorList.findIndex(grade => grade.grade == item.grade);
                gradeColorList[i].colors.push({ 'id': item.colorId, 'name': item.colorName})
              }else{
                gradeColorList.push({
                  'grade': item.grade,
                  'colors': [{
                    'id': item.colorId, 'name': item.colorName
                  }]
                });
              }
            }
            _this.setData({
              gradeColorList: gradeColorList,
            })
          }
          var selGoods = {}
          for (let index = 0; index < res.data.content.length; index++) {
            const item = res.data.content[index];
            if(_this.data.selColorId == item.colorId && _this.data.selGrade == item.grade){
              selGoods = item;
            }
          }
          console.log(selGoods,'selGoods')
          var countDownTime = 0;
          var hasBegin = false;
          if(res.data.content[0].flashSaleEndTime != 'null' && res.data.content[0].flashSaleEndTime && res.data.content[0].flashSaleEndTime != ''){
            if(new Date(res.data.content[0].flashSaleStartTime.replace(/-/g,'/')).getTime() - new Date().getTime() > 0){
              countDownTime = new Date(res.data.content[0].flashSaleStartTime.replace(/-/g,'/')).getTime() - new Date().getTime();
            }else{
              countDownTime = new Date(res.data.content[0].flashSaleEndTime.replace(/-/g,'/')).getTime() - new Date().getTime();
              hasBegin = true;
            }
          }
          console.log(countDownTime,'countDownTime')
          _this.setData({
            goods: selGoods.id != null ? selGoods : res.data.content[0],
            grade: res.data.content[0].grade,
            colorId: res.data.content[0].colorId,
            goodsBanner: [res.data.content[0].imageUrl],
            imgType: res.data.content[0].imageUrl ? checkFile(res.data.content[0].imageUrl) : 'image',
            // goodsDetailPic: [res.data.content[0].imageUrl],
            countDownTime: countDownTime,
            hasBegin: hasBegin,
          })
          _this.getGoodsPic('0');
          if(!res.data.content[0].imageUrl){
            _this.getGoodsPic('1');
          }
          _this._getGoodsCollection();
          _this._queryGoodsFreightConfig();
        }else{
          wx.showToast({
            title: '暂未获取到商品信息，请联系客服处理',
            icon: 'none',
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品图片信息
  getGoodsPic(type){
    let _this = this;
    getGoodsPicture(_this.data.item.goodsId,type)
    .then(res => {
      if(res.success){
        if(type == 0){
          _this.setData({
            goodsDetailPic: res.data,
          })
        }else if(type == 1){
          if(res.data.length > 0){
            _this.setData({
              // goodsBanner: res.data,
              goodsBanner: [res.data[0].imageUrl],
              imgType: checkFile(res.data[0].imageUrl)
            })
          }
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品规格信息
  _getGoodsSpec(){
    let _this = this;
    getGoodsSpecInfo({goodsId: _this.data.goodsId})
    .then(res => {
      if(res.success){
        if(res.data.length > 0){
          var list = _this._tidySpec(res.data,res.data[0]);
          console.log(res.data,res.data[0],'goodsSpecInfo')
          _this.setData({
            goodsSpecInfo: res.data[0],
            goodsSpecList: list,
          })
        }else{
          wx.showToast({
            title: '暂无规格信息！',
            icon: 'none',
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 整理规格信息
  _tidySpec(specList,goodsSpec){
    var map = {'name': goodsSpec.specNameOne,'label':goodsSpec.ruleNameOne,'children': []};
    var list = [map];
    specList.forEach((element) =>{
      var spec = element;
      var nums = 0;
      list.forEach((item) =>{
        if(spec.specNameOne == item['name']){
          item['children'].push(spec);
        }else{
          nums++;
        }
      });
      if(nums == list.length){
        list.push({
          'name': spec.specNameOne,
          'label': spec.ruleNameOne,
          'children': [spec]
        });
      }
    });
    console.log(list);
    return list;
  },
  // 选择规格
  selGoods(e){
    console.log(e,'父组件数据')
    if(e.detail){
      var item = JSON.parse(e.detail);
      if(item.name == 'grade'){
        this.setData({
          grade: item.id,
          colorId: item.colorId,
        })
      }
      if(item.name == 'colorId'){
        this.setData({
          colorId: item.id,
        })
      }
      this.getGoods()
    }
  },
  // 点击轮播图片
  showBannerPic(e){
    console.log(e,'点击轮播')
    var imgUrl = JSON.parse(e.detail);
    var imgType = checkFile(imgUrl);
    this.setData({
      pictureCont: imgUrl,
      imgType: imgType,
    })
    this.showPicCont();
  },
  // 点击详情图片
  showPic(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item,'item');
    this.setData({
      pictureCont: item,
      imgType: 'image',
    })
    this.showPicCont();
  },
  // 打开、关闭图片详情
  showPicCont(){
    let _this = this;
    console.log(_this.data.isShowPicContent,'isShowPicContent')
    _this.setData({
      isShowPicContent: !_this.data.isShowPicContent,
    })
  },
  // 获取购物车商品数量
  _getShoppingCartGoods(){
    let _this = this;
    getShoppingCartGoods()
    .then(res => {
      if(res.success){
        _this.setData({
          shoppingCartGoodsSum: res.data.result.length,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 查询当前商品是否收藏
  _getGoodsCollection(){
    let _this = this;
    getGoodsCollection({storehouseId: _this.data.goods.storehouseId,areaId: _this.data.goods.areaId,goodsId: _this.data.goods.goodsId})
    .then(res => {
      if(res.success){
        if(res.data.content.length > 0){
          _this.setData({
            collectId: res.data.content[0].id,
          })
          console.log(_this.data.collectId,'收藏商品信息')
        }else{
          _this.setData({
            collectId: '',
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 收藏商品
  collect(){
    let _this = this;
    goodsCollection({goodsId: _this.data.goods.goodsId,isDelete: _this.data.goods.isCollect,storehouseId: _this.data.goods.storehouseId,areaId: _this.data.goods.areaId,id: _this.data.collectId})
    .then(res => {
      if(res.success){
        _this.getGoods();
        wx.showToast({
          title: _this.data.goods.isCollect == 0 ? '收藏成功' : '取消收藏',
          icon: 'none',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 添加购物车
  addShoppingCard(){
    let _this = this;
    var shoppingCartId = wx.getStorageSync('shoppingCartId') ? wx.getStorageSync('shoppingCartId') : '';
    updateShoppingCartGoods({goodsDetailsId: _this.data.goods.id,isSelect: '1',id: shoppingCartId})
    .then(res => {
      if(res.success){
        _this._getShoppingCartGoods();
        wx.showToast({
          title: '已成功加入购物车',
          icon: 'none',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 立即购买
  async buy(){
    let _this = this;
    try {
      var hasClose = await _this._queryGoodsCloseConfig();
      console.log(hasClose,'hasClose')
      if(hasClose != ''){
        wx.showToast({
          title: hasClose,
          icon: 'none',
        })
        return;
      }
    } catch (error) {
      console.log(error,'error')
      wx.showToast({
        title: error,
      })
      return;
    }
    var userId = wx.getStorageSync('userId');
    var goodsCard = [{
      id: '',
      brandId: _this.data.goods.brandId,
      userId: userId,
      goodsId: _this.data.goods.goodsId,
      cateId: _this.data.goods.cateId,
      quantity: 1,
      addToCartPrice: _this.data.goods.sellingPrice,
      isSelect: 1,
      goodsName: _this.data.goods.goodsName,
      imageUrl: _this.data.goods.imageUrl ? _this.data.goods.imageUrl : _this.data.goodsBanner[0],
      areaId: _this.data.goods.areaId,
      colorName: _this.data.goods.colorName,
      description: _this.data.goods.description,
      goodsDetailsId: _this.data.goods.id,
      goodsListsId: _this.data.goods.id,
      grade: _this.data.goods.grade,
      isFlashSale: _this.data.goods.isFlashSale,
      remarks: _this.data.goods.remarks,
      flashSaleEndTime: _this.data.goods.flashSaleEndTime,
      flashSaleStartTime: _this.data.goods.flashSaleStartTime,
      specName: _this.data.goods.specName,
      storehouseId: _this.data.goods.storehouseId,
      stock: _this.data.goods.stock,
      merchantId: _this.data.goods.merchantId,
    }]
    if(_this.data.goods.isFlashSale == '1'){
      if(new Date(_this.data.goods.flashSaleStartTime.replace(/-/g,'/')).getTime() - new Date().getTime() > 0){
        wx.showToast({
          title: '当前产品秒杀还未开始，请更换其他商品！',
          icon: 'none'
        })
        return;
      }
      if(new Date(_this.data.goods.flashSaleEndTime.replace(/-/g,'/')).getTime() - new Date().getTime() <= 0){
        wx.showToast({
          title: '当前产品秒杀已结束，请更换其他商品！',
          icon: 'none'
        })
        return;
      }
    }
    wx.navigateTo({
      url: `/pages/Orders/SubmitOrder/SubmitOrder?item=${JSON.stringify(goodsCard)}`,
    })
  },
  // 打开客服
  contact(){
    let _this = this;
    wx.openCustomerServiceChat({
      extInfo: {
        url: _this.data.contactUrl,
      },
      corpId: _this.data.contactId,
    })
  },
  // 查询商品分区信息
  _queryGoodsArea(){
    let _this = this;
    queryGoodsCommonConfig({type: '1'})
    .then(async res => {
      if(res.success){
        if(res.data.content.length > 0){
          var areaName = ''
          for(let i = 0; i < res.data.content.length; i++){
            let cate = res.data.content[i];
            if(cate.id == _this.data.item.areaId){
              areaName = cate.name
            }
          }
          _this.setData({
            areaName: areaName,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品购买记录
  _queryGoodsPurchaseRecord(){
    let _this = this;
    queryGoodsPurchaseRecord({storehouseId: _this.data.item.storehouseId})
    .then(res => {
      if(res.success){
        _this.setData({
          goodsRecord: res.data.content,
          goodsRecordTotal: res.data.totalElements,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取商品运费配置
  _queryGoodsFreightConfig(){
    let _this = this;
    queryGoodsFreightConfig({storehouseId: _this.data.goods.storehouseId})
    .then(res => {
      if(res.success){
        var integralStandard = 0;
        if(res.data.content.length > 0){
          integralStandard = res.data.content[0].integralStandard;
        }
        // 查询用户是否免运费
        queryGoodsFreeFreightMark({storehouseId: _this.data.goods.storehouseId})
        .then(res => {
          if(res.success){
            _this.setData({
              isReachStandard: res.data.isFreeFreight,
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 展示免运费规则
  mianyunfeiguize(){
    let _this = this;
    queryAppInforMation({infoType: '15',title: '打包费及运输费规则',page: _this.data.page})
      .then(res => {
        if(res.success){
          if(res.data.content.length > 0){
            var item = res.data.content[0];
            wx.navigateTo({
              url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(item.imgUrl)}&title=${JSON.stringify(item.title)}`,
            })
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
  },
  // 获取商店打烊时间
  _queryGoodsCloseConfig(){
    let _this = this;
    return new Promise((resolve,reject) => {
      queryGoodsCloseConfig({storehouseId: _this.data.item.storehouseId,merchantId: _this.data.goods.merchantId})
      .then(res => {
        if(res.success){
          var showCloseTime = '';
          var closeStartTime = res.data.content.length > 0 ? res.data.content[0].startTime.substring(0,5) : '';
          var closeEndTime = res.data.content.length > 0 ? res.data.content[0].endTime.substring(0,5) : '';
          if(closeStartTime != '' && closeEndTime != ''){
            var nowH = new Date().getHours();
            var nowM = new Date().getMilliseconds();
            var nowTime = new Date().getTime();
            // 判断打烊时间是否跨天
            var startH = parseInt(closeStartTime.substring(0,2));
            var endH = parseInt(closeEndTime.substring(0,2));
            var startT = new Date(`${new Date().getFullYear()}/${new Date().getMonth() + 1}/${new Date().getDate()} ${closeStartTime}`).getTime();
            var endT = new Date(`${new Date().getFullYear()}/${new Date().getMonth() + 1}/${new Date().getDate()} ${closeEndTime}`).getTime();
            console.log(nowH,'nowH');
            console.log(startH,'startH');
            console.log(endH,'endH');
              console.log(startT,'startT')
              console.log(endT,'endT')
            if(startH > endH){
              // 跨天，开始时间大于结束时间
              if(nowTime < endT || nowTime > startT){
                showCloseTime = `商家已打烊，${closeStartTime}-${closeEndTime}为休息时间`;
              }
            }else{
              if(nowTime > startT && nowTime < endT){
                showCloseTime = `商家已打烊，${closeStartTime}-${closeEndTime}为休息时间`;
              }
            }
          }
          resolve(showCloseTime);
        }else{
          reject(res.errMessage)
        }
      })
    })
  }
})